<?php

namespace app\h5\v1\controller;

use app\common\ApiBase;
use app\model\OrderProduct;
use app\model\OrderVipcart;
use app\model\User;
use app\model\UserBill;
use app\model\VipOrder;
use app\service\AlipayService;
use app\service\AppleService;
use app\service\WechatService;
use polymerize\order\service\PayModelService;
use support\Request;
use support\Response;

class PayCallback extends ApiBase
{
    //阿里支付h5回调
    public function alipay(Request $request): Response
    {
        $out_trade_no = $request->get('out_trade_no', '');
        if (empty($out_trade_no)) return $this->apiFailed('订单号不存在');

        $orderNo   = getFilterStr($out_trade_no);
        $where[]   = ['order_no', '=', $orderNo];
        $orderInfo = VipOrder::getOne($where);
        if (!$orderInfo) return $this->apiFailed('订单不存在');
        if ($orderInfo['status'] == 1) return $this->apiSuccess(['pay_status' => 1], '已支付', 200);
        $uid = $orderInfo['uid'];

        $query = AlipayService::instance()->_query($orderNo);
        if (is_array($query) && isset($query['alipay_trade_query_response']['trade_status'])) {
            if ($query['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS') {
                $payTime = $query['alipay_trade_query_response']['send_pay_date'];
                $tradeNo = $query['alipay_trade_query_response']['trade_no'];
                //更新用户会员表
                $res = PayModelService::instance()->updateModelByPaySuccess($orderNo, $uid, $orderInfo['vip_type'], $orderInfo['day'], $payTime, $tradeNo);
                return ($res['code'] == 200) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed('支付失败');
            }
        }

        return $this->apiFailed('支付失败');
    }


    //        array(6) {
//        ["id"]=>
//  string(36) "a7cb1a00-0e6357fe518"
//        ["create_time"]=>
//  string(25) "2022-08-29T23:06:16+08:00"
//        ["resource_type"]=>
//  string(16) "encrypt-resource"
//        ["event_type"]=>
//  string(19) "TRANSACTION.SUCCESS"
//        ["summary"]=>
//  string(12) "支付成功"
//        ["resource"]=>
//  array(5) {
//            ["original_type"]=>
//    string(11) "transaction"
//            ["algorithm"]=>
//    string(16) "AEAD_AES_256_GCM"
//            ["ciphertext"]=>
//    string(600) "j8LrYgoD81dXHDStYjuhDUFdTuWA54K16dxcimlRqyvkujrFzQhTHhKvMLuHvgAJ5aZ/gOmxTq0GsmQvn+OZCkryJX/ouDo5hm7chDicUaedWCihfo/cXg1CkoWo="
//            ["associated_data"]=>
//    string(11) "transaction"
//            ["nonce"]=>
//    string(12) "1EoSE4PF"
//  }
//}
    //微信支付回调
    //h5/payCallback/wechat/
    public function wechat(Request $request): Response
    {
        $response_json = $request->rawBody();
        if (empty($response_json)) return $this->apiFailed('参数不存在');
        $response = json_decode($response_json, true);
        if (empty($response)) return $this->apiFailed('参数错误');
        $response = WechatService::instance()->decryptToString($response['resource']['associated_data'], $response['resource']['nonce'], $response['resource']['ciphertext']);
        $response = json_decode($response, true);
        if (empty($response)) return $this->apiFailed('解密错误');
        if ($response['trade_state'] !== 'SUCCESS') return $this->apiFailed('失败');

        $orderNo = $response['out_trade_no'] ?? '';
        if (empty($orderNo)) return $this->apiFailed('订单号不存在');
        $where1[]  = ['order_no', '=', $orderNo];
        $orderInfo = UserBill::getOne($where1);
        if (!$orderInfo) return $this->apiFailed('订单不存在');
        if ($orderInfo['status'] == 1) return $this->apiSuccess(['pay_status' => 1], '已支付', 200);
        $uid = $orderInfo['user_id'];

        //保险去微信查询订单信息
        $query = WechatService::instance()->_query($orderNo);
        if (is_array($query) && isset($query['trade_state'])) {
            if ($query['trade_state'] == 'SUCCESS') {
                //"2022-05-24T19:33:40+08:00" to "2022-05-24 19:33:40"
                $payTime = getBeforeString(str_replace(array('T', 'Z'), ' ', $query['success_time']), '+');
                $tradeNo = $query['transaction_id'];
                //更新用户会员表
                $res = PayModelService::instance()->updateModelByCZPaySuccess($orderNo, $uid, $payTime, $tradeNo);
                return ($res['code'] == 200) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed('支付失败');
            }
        }

        $msg = isset($query['trade_state_desc']) ? $query['trade_state_desc'] : '支付失败';
        return $this->apiFailed($msg);
    }

    //h5/payCallback/wechatRechargeDiscountPay/
    //购买充值卡
    public function wechatRechargeDiscountPay(Request $request): Response
    {
        $response_json = $request->rawBody();
        if (empty($response_json)) return $this->apiFailed('参数不存在');
        $response = json_decode($response_json, true);
        if (empty($response)) return $this->apiFailed('参数错误');
        $response = WechatService::instance()->decryptToString($response['resource']['associated_data'], $response['resource']['nonce'], $response['resource']['ciphertext']);
        $response = json_decode($response, true);
        if (empty($response)) return $this->apiFailed('解密错误');
        if ($response['trade_state'] !== 'SUCCESS') return $this->apiFailed('失败');

        $orderNo = $response['out_trade_no'] ?? '';
        if (empty($orderNo)) return $this->apiFailed('订单号不存在');
        $where1[]  = ['order_no', '=', $orderNo];
        $orderInfo = UserBill::getOne($where1);
        if (!$orderInfo) return $this->apiFailed('订单不存在');
        if ($orderInfo['status'] == 1) return $this->apiSuccess(['pay_status' => 1], '已支付', 200);
        $uid = $orderInfo['user_id'];

        //保险去微信查询订单信息
        $query = WechatService::instance()->_query($orderNo);
        if (is_array($query) && isset($query['trade_state'])) {
            if ($query['trade_state'] == 'SUCCESS') {
                //"2022-05-24T19:33:40+08:00" to "2022-05-24 19:33:40"
                $payTime = getBeforeString(str_replace(array('T', 'Z'), ' ', $query['success_time']), '+');
                $tradeNo = $query['transaction_id'];
                //更新用户会员表
                $res = PayModelService::instance()->updateModelByCZPaySuccess($orderNo, $uid, $payTime, $tradeNo);
                return ($res['code'] == 200) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed('支付失败');
            }
        }

        $msg = isset($query['trade_state_desc']) ? $query['trade_state_desc'] : '支付失败';
        return $this->apiFailed($msg);
    }

    //h5/payCallback/wechatVipcartPay/
    //购买会员卡
    public function wechatVipcartPay(Request $request): Response
    {
        $response_json = $request->rawBody();
        if (empty($response_json)) return $this->apiFailed('参数不存在');
        $response = json_decode($response_json, true);
        if (empty($response)) return $this->apiFailed('参数错误');
        $response = WechatService::instance()->decryptToString($response['resource']['associated_data'], $response['resource']['nonce'], $response['resource']['ciphertext']);
        $response = json_decode($response, true);
        if (empty($response)) return $this->apiFailed('解密错误');
        if ($response['trade_state'] !== 'SUCCESS') return $this->apiFailed('失败');

        $orderNo = $response['out_trade_no'] ?? '';
        if (empty($orderNo)) return $this->apiFailed('订单号不存在');
        $where1[]  = ['order_no', '=', $orderNo];
        $orderInfo = OrderVipcart::getOne($where1);
        if (!$orderInfo) return $this->apiFailed('订单不存在');
        if ($orderInfo['status'] == 1) return $this->apiSuccess(['pay_status' => 1], '已支付', 200);
        $uid = $orderInfo['user_id'];

        //保险去微信查询订单信息
        $query = WechatService::instance()->_query($orderNo);
        if (is_array($query) && isset($query['trade_state'])) {
            if ($query['trade_state'] == 'SUCCESS') {
                //"2022-05-24T19:33:40+08:00" to "2022-05-24 19:33:40"
                $payTime = getBeforeString(str_replace(array('T', 'Z'), ' ', $query['success_time']), '+');
                $tradeNo = $query['transaction_id'];
                //更新用户会员表
                $data = [
                    'status'   => 1,
                    'pay_time' => $payTime,
                    'trade_no' => $tradeNo,
                    'u_time'   => myDate(),
                ];
                $res  = OrderVipcart::where('id', $orderInfo['id'])->update($data);
                //更新用户累计消费金额
                $sumConsume = User::getField([['id', $orderInfo['user_id']]], 'sum_consume');
                $data       = [
                    'sum_consume' => $sumConsume + $orderInfo['discount_price'],
                    'u_time'      => myDate(),
                ];
                $res2       = User::where('id', $orderInfo['user_id'])->update($data);

                return ($res && $res2) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed('支付失败');
            }
        }

        $msg = isset($query['trade_state_desc']) ? $query['trade_state_desc'] : '支付失败';
        return $this->apiFailed($msg);
    }

    //h5/payCallback/wechatProductPay/
    //购买产品
    public function wechatProductPay(Request $request): Response
    {
        $response_json = $request->rawBody();
        if (empty($response_json)) return $this->apiFailed('参数不存在');
        $response = json_decode($response_json, true);
        if (empty($response)) return $this->apiFailed('参数错误');
        $response = WechatService::instance()->decryptToString($response['resource']['associated_data'], $response['resource']['nonce'], $response['resource']['ciphertext']);
        $response = json_decode($response, true);
        if (empty($response)) return $this->apiFailed('解密错误');
        if ($response['trade_state'] !== 'SUCCESS') return $this->apiFailed('失败');

        $orderNo = $response['out_trade_no'] ?? '';
        if (empty($orderNo)) return $this->apiFailed('订单号不存在');
        $where1[]  = ['order_no', '=', $orderNo];
        $orderInfo = OrderProduct::getOne($where1);
        if (!$orderInfo) return $this->apiFailed('订单不存在');
        if ($orderInfo['status'] == 1) return $this->apiSuccess(['pay_status' => 1], '已支付', 200);
        $uid = $orderInfo['user_id'];

        //保险去微信查询订单信息
        $query = WechatService::instance()->_query($orderNo);
        if (is_array($query) && isset($query['trade_state'])) {
            if ($query['trade_state'] == 'SUCCESS') {
                //"2022-05-24T19:33:40+08:00" to "2022-05-24 19:33:40"
                $payTime = getBeforeString(str_replace(array('T', 'Z'), ' ', $query['success_time']), '+');
                $tradeNo = $query['transaction_id'];
                //更新用户会员表
                $data = [
                    'status'   => 1,
                    'pay_time' => $payTime,
                    'trade_no' => $tradeNo,
                    'u_time'   => myDate(),
                ];
                $res  = OrderProduct::where('id', $orderInfo['id'])->update($data);

                //更新用户累计消费金额
                $sumConsume = User::getField([['id', $orderInfo['user_id']]], 'sum_consume');
                $data       = [
                    'sum_consume' => $sumConsume + $orderInfo['discount_price'],
                    'u_time'      => myDate(),
                ];
                $res2       = User::where('id', $orderInfo['user_id'])->update($data);

                return ($res && $res2) ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed('支付失败');
            }
        }

        $msg = isset($query['trade_state_desc']) ? $query['trade_state_desc'] : '支付失败';
        return $this->apiFailed($msg);
    }

    //苹果支付回调
    //h5/payCallback/apple
    public function apple(Request $request): Response
    {
        $signedPayload = $request->post('signedPayload', '');
        if (!$signedPayload) return $this->apiFailed('the notify data is empty');

        $res = AppleService::instance()->appleNotify($signedPayload);

        return $res['code'] == 200 ? $this->apiSuccess(['pay_status' => 1]) : $this->apiFailed($res['msg']);
    }

}